package com.ikingtech.platform.service.system.menu.service;

import com.ikingtech.framework.sdk.application.api.ApplicationMenuApi;
import com.ikingtech.framework.sdk.enums.domain.DomainEnum;
import com.ikingtech.framework.sdk.enums.system.menu.MenuJumpTypeEnum;
import com.ikingtech.framework.sdk.enums.system.menu.MenuTypeEnum;
import com.ikingtech.framework.sdk.enums.system.menu.MenuViewTypeEnum;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.menu.entity.MenuDO;
import lombok.RequiredArgsConstructor;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class ApplicationMenuService implements ApplicationMenuApi {

    private final MenuService service;

    @Override
    public void saveOrUpdate(String pageId,
                             String pageName,
                             String parentPageId,
                             String icon,
                             String link,
                             String component,
                             String tenantCode,
                             String appCode) {
        MenuDO entity = this.service.getByPermissionCode(pageId, tenantCode);
        String parentMenuId = Tools.Str.EMPTY;
        if (Tools.Str.isNotBlank(parentPageId)) {
            parentMenuId = this.service.getIdByPermissionCode(parentPageId, tenantCode);
        }
        if (null == entity) {
            entity = new MenuDO();
            entity.setId(Tools.Id.uuid());
            entity.setDomainCode(DomainEnum.APPLICATION.name());
            entity.setTenantCode(tenantCode);
            entity.setAppCode(appCode);
            entity.setName(pageName);
            entity.setParentId(parentMenuId);
            entity.setPermissionCode(pageId);
            entity.setIcon(icon);
            entity.setLink(link);
            entity.setMenuType(MenuTypeEnum.MENU.name());
            entity.setMenuViewType(MenuViewTypeEnum.MANAGE.name());
            entity.setJumpType(MenuJumpTypeEnum.FRONT_ROUTE.name());
            entity.setComponent(component);
            entity.setVisible(true);
            entity.setFramework(true);
            entity.setBreadcrumb(true);
            entity.setSidebar(true);
            entity.setSortOrder(this.service.getMaxSortOrder(parentMenuId, appCode) + 1);
        } else {
            entity.setParentId(parentMenuId);
            entity.setIcon(icon);
            entity.setName(pageName);
            entity.setPermissionCode(pageId);
            entity.setLink(link);
            entity.setComponent(component);
        }
        entity.setFullPath(this.service.parseFullPath(parentMenuId, entity.getId()));
        this.service.saveOrUpdate(entity);
    }

    @Override
    public void removeByPermissionCode(String pageId, String tenantCode, String appCode) {
        this.service.removeByPermissionCode(pageId, tenantCode, appCode);
    }
}
